package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.admin.entity.AdChannel;
import com.heima.admin.mapper.AdChannelMapper;
import com.heima.admin.service.AdChannelService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.dtos.PageResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.exception.LeadException;
import com.heima.common.util.BeanHelper;
import com.heima.model.admin.dtos.ChannelDto;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;


import java.util.Date;
import java.util.List;

/**
 * <p>
 * 频道信息表 服务实现类
 * </p>
 *
 * @author HM
 * @since 2022-10-15
 */
@Service
public class AdChannelServiceImpl extends ServiceImpl<AdChannelMapper, AdChannel> implements AdChannelService {

    /**
     * 分页查询频道的方法
     *
     * @param dto
     * @return
     */
    @Override
    public PageResult<ChannelDto> findByPage(ChannelDto dto) {
//设置分页条件
        IPage<AdChannel> iPage = new Page<>(dto.getPage(), dto.getSize());
//设置查询条件
        LambdaQueryWrapper<AdChannel> queryWrapper = new LambdaQueryWrapper<>();

        queryWrapper.like(StringUtils.isNotBlank(dto.getName()), AdChannel::getName, dto.getName());
        //核心分页查询
        IPage<AdChannel> adChannelIPage = page(iPage, queryWrapper);
        //对象转换
        if (CollectionUtils.isEmpty(adChannelIPage.getRecords())) {
            throw new LeadException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        List<ChannelDto> channelDtos = BeanHelper.copyWithCollection(adChannelIPage.getRecords(), ChannelDto.class);

        return new PageResult<>(dto.getPage(),
                dto.getSize(),
                adChannelIPage.getTotal(),
                channelDtos);
    }

//    @Override
//    public void saveda(ChannelDto dto) {
//
//        if(StringUtils.isBlank(dto.getName())){
//            throw new LeadException(AppHttpCodeEnum.PARAM_REQUIRE);
//        }
//        AdChannel adChannel = BeanHelper.copyProperties(dto, AdChannel.class);
//        adChannel.setCreatedTime(new Date());
//        save(adChannel);
//    }

    @Override
    public void updateda(ChannelDto dto) {
        if (dto.getId()==null&&StringUtils.isBlank(dto.getName())){
            throw  new LeadException(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        AdChannel adChannel = BeanHelper.copyProperties(dto, AdChannel.class);
        updateById(adChannel);
    }
}
